package com.talkweb.citypickerview.style.citythreelist;


import com.talkweb.citypickerview.ResourceTable;
import com.talkweb.citypickerview.style.citylist.bean.CityInfoBean;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：liji on 2017/12/16 15:13
 * 邮箱：lijiwork@sina.com
 * QQ ：275137657
 */

public class CityAdapter extends BaseItemProvider {
    List<CityInfoBean> cityList = new ArrayList<>();
    
    Context context;
    
    private OnItemSelectedListener mOnItemClickListener;
    
    public void setOnItemClickListener(OnItemSelectedListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public int getCount() {
        return cityList != null ? cityList.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return cityList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        MyViewHolder holder;
        if (component == null) {
            holder = onCreateViewHolder(componentContainer, getItemComponentType(i));
            component = holder.itemView;
            component.setTag(holder);
        } else {
            holder = (MyViewHolder) component.getTag();

        }

        onBindViewHolder(holder, i);

        return component;
    }

    public interface OnItemSelectedListener {
        /**
         * item点击事件
         *
         * @param view
         * @param position
         */
        void onItemSelected(Component view, int position);
    }
    
    public CityAdapter(Context context, List<CityInfoBean> cityList) {
        this.cityList = cityList;
        this.context = context;
    }
    
    public MyViewHolder onCreateViewHolder(ComponentContainer parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(
                LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_citylist, parent, false));
        return holder;
    }
    
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.tv.setText(cityList.get(position).getName());
        holder.tv.setClickedListener(v -> {
            if (mOnItemClickListener != null && position < cityList.size()) {
                mOnItemClickListener.onItemSelected(v, position);
            }
        });
    }
    
    class MyViewHolder {

        Component itemView;
        Text tv;
        
        public MyViewHolder(Component view) {
            itemView = view;
            tv = (Text) view.findComponentById(ResourceTable.Id_default_item_city_name_tv);
        }
    }
}
